package com.gw.predicate;

import com.alibaba.cloud.commons.lang.StringUtils;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
@Component
public class AgeRoutePredicateFactory  extends AbstractRoutePredicateFactory<AgeRoutePredicateFactory.Config> {
    public static final String MIN_KEY = "minAge";
    public static final String MAX_KEY = "maxAge";

    public AgeRoutePredicateFactory() {
        super(Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("minAge", "maxAge");
    }

    public Predicate<ServerWebExchange> apply(Config config) {
       // Assert.isTrue(config.getDatetime1().isBefore(config.getDatetime2()), config.getDatetime1() + " must be before " + config.getDatetime2());
        return new GatewayPredicate() {
            public boolean test(ServerWebExchange serverWebExchange) {
                //ZonedDateTime now = ZonedDateTime.now();
                // 1. 获取参数中的age的值
                String age = serverWebExchange.getRequest().getQueryParams().getFirst("age");
                System.out.println("age 的值是:"+age);
                int age1=0;
                if(StringUtils.isNotBlank(age)){
                 age1=Integer.parseInt(age);
                }
                //
                return age1>=config.getMinAge()&&age1<=config.getMaxAge();
            }

            public String toString() {
                return String.format("Between: %s and %s", config.getMinAge(), config.getMaxAge());
            }
        };
    }

    @Validated
    public static class Config {
        @NotNull
        private Integer minAge;
        @NotNull
        private Integer maxAge;

        public Config() {
        }

        public Integer getMinAge() {
            return minAge;
        }

        public void setMinAge(Integer minAge) {
            this.minAge = minAge;
        }

        public Integer getMaxAge() {
            return maxAge;
        }

        public void setMaxAge(Integer maxAge) {
            this.maxAge = maxAge;
        }
    }
}
